'use strict'

const electron = require('electron')
const {
  app,
  BrowserWindow,
  ipcMain,
  Menu,
} = electron

const {
  loginHandle,
  urlHandle,
  saveHandle,
} = require('./controller')

let isDevelopment = true

if (isDevelopment) {
  require('electron-reload')(__dirname, {
    ignored: /node_modules|[\/\\]\./
  })
}

// let workAreaSize = null
let mainWnd = null

const template = [
  {
    label: app.getName(),
    submenu: [
      {role: 'about'},
      {type: 'separator'},
      {role: 'services', submenu: []},
      {type: 'separator'},
      {role: 'hide'},
      {role: 'hideothers'},
      {role: 'unhide'},
      {type: 'separator'},
      {role: 'quit'}
    ]
  }, {
    label: '问诊',
    submenu: [
      {
        label: '新建',
        accelerator: 'CommandOrControl+N',
        click() { 
          mainWnd.webContents.send('New')
        }
      }, {
        label: '保存',
        accelerator: 'CommandOrControl+S',
        click() { console.log('Save')}
      }, {
        label: '关闭',
        accelerator: 'CommandOrControl+F4',
        click() { 
          mainWnd.webContents.send('Close')
        }
      }
    ]
  }
]

function createMainWnd() {
  mainWnd = new BrowserWindow({
    title: 'HIS',
    width: 480,
    height: 380,
    center: true,
    autoHideMenuBar: true,
    icon: './public/images/appIcon.png',
    titleBarStyle: 'hidden-inset',
    frame: false,
    resizable: false,
    show: false,
    webPreferences: {
      javascript: true,
      plugins: true,
      webSecurity: false,
    },
  })

  mainWnd.loadURL(`file://${__dirname}/view/index.html`)
  // mainWnd.setFullScreen(true)
  // mainWnd.webContents.openDevTools ()

  mainWnd.on('closed', () => {
    mainWnd = null
  })

  mainWnd.once('ready-to-show', () => {
    mainWnd.show()
    // workAreaSize = electron.screen.getPrimaryDisplay().workAreaSize
  })
}

app.on('ready', createMainWnd)

const isSecondInstance = app.makeSingleInstance(() => {
  if (mainWnd) {
    if (mainWnd.isMinimized()) mainWnd.restore()
    mainWnd.focus()
    mainWnd.webContents.openDevTools()
  }
})
if (isSecondInstance) {
  app.quit()
}

app.on('window-all-closed', () => {
  app.quit()
})

ipcMain.on('exitApp', () => {
  app.quit()
})

ipcMain.on('login', (e, arg) => {
  loginHandle(arg.usr, arg.pwd, (res) => {
    if (res.status === 'success') {
      mainWnd.webContents.send('loginSuccess')
      setTimeout(() => {
        // mainWnd.setSize(workAreaSize.width, workAreaSize.height)
        // mainWnd.center()
        mainWnd.setFullScreen(true)
        Menu.setApplicationMenu(Menu.buildFromTemplate(template))
        mainWnd.webContents.openDevTools ()
      }, 200)
    } else {
      setTimeout(() => {
        mainWnd.webContents.send('loginFailure')
      }, 1000)
    }
  })
})

ipcMain.on('url', (e, arg) => {
  setTimeout(() => e.returnValue = {status: 'failure', datas: [], drugs: []}, 1000)
  urlHandle(arg, (data) => {
    e.returnValue = data
  })
})

let patients = []

ipcMain.on('patient', (e, arg) => {
  arg.saved = false
  let stillExist = false
  for (let k = 0; k < patients.length; k += 1) {
    if (patients[k]._id == arg._id) {
      if (arg.state !== undefined) patients[k].state = arg.state
      if (arg.medicines !== undefined) patients[k].medicines = arg.medicines
      stillExist = true
      break
    }
  }
  if (stillExist === false) {
    patients.push(arg)
  }
})

ipcMain.on('getPatient', (e, arg) => {
  for (let k = 0; k < patients.length; k += 1) {
    if (patients[k]._id == arg) {
      e.returnValue = patients[k]
      return
    }
  }
  e.returnValue = null
})


ipcMain.on('save', (e, arg) => {
  // TODO:
  // 1. 已经保存过的update
  // 2. history来的update
  for (let k = 0; k < patients.length; k += 1) {
    if (patients[k]._id === arg._id) {
      patients[k].saved = true
      console.log(patients)
      break
    }
  }
  saveHandle(arg, patients, (body) => {
    e.sender.send('saved', JSON.parse(body))
  })
})